package com.pancm.datacollector.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.core.authority.AuthorityUtils;
import java.util.Arrays;

/**
 * Spring Security 配置类
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${security.user.name:admin}")
    private String username;

    @Value("${security.user.password:admin123}")
    private String password;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/collector/**").authenticated()  // 需要认证的路径
                .anyRequest().permitAll()                     // 其他路径允许匿名访问
            .and()
            .httpBasic()                                     // 启用Basic认证
            .and()
            .csrf().disable();                               // 禁用CSRF保护
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = new User(
            username,
            passwordEncoder().encode(password),
            true, true, true, true,
            AuthorityUtils.createAuthorityList("ROLE_ADMIN")
        );

        return new InMemoryUserDetailsManager(Arrays.asList(user));
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
} 